<template>
  <div class=" bg-white page-content content" style="height: calc(100vh - 138px)">
    <div class="flex column no-wrap full-height">
      <!-- 搜索区 -->
      <ListSearch :connect-status="connectStatus" @resetSearch="resetSearch" @searchList="search" ref="listSearch"/>
      <!-- 操作 -->
      <div style="display: flex;padding:0 20px;margin-bottom: 10px;" class="form-inline">
        <q-btn
          class="btn margin-r-10"
          outline
          color="primary"
          @click="initGateway"
          label="网关初始化"
        />
        <q-btn
          class="btn margin-r-10"
          outline
          color="primary"
          @click="patchCreate"
          label="批量新建网关"
        />
        <q-btn class="btn"
               outline color="primary"
               @click="exportExcel"
               :disable="dataInfo.length === 0 || exportLoading"
               :loading="exportLoading">导出</q-btn>
      </div>

      <div class="table-wrapper">
              <ListTable ref="table"
                         :total="total"
                         :table-data="dataInfo"
                         :noPagination="noPagination"
                         :connectStatusObj="connectStatusObj"
                         :table-loading="loading"
                         @deleteSuccess="searchList(queryParams)"
                         @changeData="searchList(queryParams)"
                         @changePagination="changePagination"/>
      </div>
    </div>

    <NewGateway ref="newGateway" :products="products" @success="successGateway"></NewGateway>

    <PatchCreateGateway ref="patchCreateDialog" @success="searchList"></PatchCreateGateway>
  </div>
</template>

<script>
import ListSearch from './components/list-components/list-search'
import ListTable from './components/list-components/list-table'
import PatchCreateGateway from './components/list-components/patch-create-gateway'
import { boxQueryList } from '../../boot/miot/list'
import moment from 'moment'
import NewGateway from './components/list-components/new-gateway.vue'
import { downloadMiotData, getPlcProducts } from '../../boot/miot/plc-list'
import _ from 'lodash'

export default {
  name: 'miot-list-v2',
  components: {
    ListSearch,
    ListTable,
    PatchCreateGateway,
    NewGateway
  },
  data () {
    return {
      params: {
        startDate: '',
        endDate: '',
        startLastOnlineTime: '',
        endLastOnlineTime: '',
        deviceId: null,
        boxId: null,
        assetNum: null,
        connectStatus: null,
        deploymentStatus: null,
        onLineStatus: null,
        deviceType: '1',
        pageNum: null,
        pageSize: null
      },
      loading: false,
      dataInfo: [],
      total: 0,
      queryParams: null,
      products: [],
      pagination: {
        // 页码
        page: 1,
        // 每页条数
        rowsPerPage: 15,
        // 总条数
        rowsNumber: 0
      },
      connectStatus: [{ label: '全部', value: null }, { label: '未激活', value: 'inactivated' }, { label: '在线', value: 'online' }, { label: '离线', value: 'offline' }],
      exportLoading: false
    }
  },
  computed: {
    connectStatusObj () {
      const obj = {}
      this.connectStatus.forEach(item => {
        obj[item.value] = item.label
      })
      return obj
    },
    noPagination () {
      return !!this.params.deploymentStatus ||
        !!this.params.onLineStatus ||
        !!this.params.connectStatus ||
        !!this.params.startLastOnlineTime ||
        !!this.params.startDate
    }
  },
  created () {
    this.searchList()
    this.getPlcProductInfo()
  },
  methods: {
    // 重置
    resetSearch () {
      this.queryParams = null
    },
    // 查询
    async searchList (queryParams) {
      if (queryParams) {
        this.queryParams = queryParams
        this.params.boxId = queryParams.gateWayId
        this.params.deploymentStatus = queryParams.deploymentStatus
        this.params.onLineStatus = queryParams.onLineStatus
        this.params.deviceId = queryParams.deviceId
        this.params.deviceType = queryParams.deviceType
        this.params.startDate = queryParams.date[0]
        this.params.endDate = queryParams.date[1]
        this.params.startLastOnlineTime = queryParams.lastOnlineTime[0]
        this.params.endLastOnlineTime = queryParams.lastOnlineTime[1]
        this.params.connectStatus = queryParams.connectStatus
      }
      // 如果不需要分页的话
      if (this.noPagination) {
        this.params.pageNum = null
        this.params.pageSize = null
      } else {
        this.params.pageNum = this.pagination.page
        this.params.pageSize = this.pagination.rowsPerPage
      }
      this.loading = true
      try {
        const { data } = await boxQueryList(this.params)
        if (data && data.list && data.list.length > 0) {
          data.list.forEach(item => {
            item.deviceCount = item.deviceInfo?.length || 0
            item.deployedDate = this.formatDate(item.deployedDate)
            item.lastOnlineTime = this.formatDate(item.lastOnlineTime)
            item.lastOfflineTime = this.formatDate(item.lastOfflineTime)
            item.prodId = this.getProdId(item.boxId)
          })
          this.dataInfo = data.list
          this.total = data.total
        } else {
          this.dataInfo = []
        }
      } catch (e) {
      } finally {
        this.loading = false
      }
    },
    changePagination (val) {
      this.pagination = val
    },
    // 批量创建
    patchCreate () {
      this.$refs.patchCreateDialog.showDialog()
    },
    // 网关初始化
    initGateway () {
      this.$refs.newGateway.showDialog()
    },
    // 获取产品列表
    async getPlcProductInfo () {
      const { data } = await getPlcProducts()
      if (data?.length) {
        this.products = data
      }
    },
    // 获取显示的prodid
    getProdId (boxId) {
      if (!boxId) return '--'
      try {
        const data = boxId.split('_')
        if (data.length === 1) return data[0]
        if (data.length === 2) return data[1]
      } catch (e) {
        return '--'
      }
    },
    formatDate (date) {
      if (!date) return '--'
      if (isNaN(Number(date))) {
        return moment(date).format('YYYY-MM-DD HH:mm:ss')
      }
      return moment(Number(date)).format('YYYY-MM-DD HH:mm:ss')
    },
    async successGateway (gatewayId) {
      try {
        await this.searchList(this.queryParams)
        if (gatewayId) {
          const info = this.dataInfo.find(item => item.prodId === gatewayId)
          if (!info || info.onLineStatus !== 'ONLINE') {
            this.$message.warning('设备已离线，请检查网关网络')
            return
          }
          this.$router.push({
            name: 'miotDetail',
            query: {
              boxId: info.boxId,
              deployedDate: info.deployedDate,
              boxStatus: info.boxStatus,
              wanCfg: info.wanCfg ? info.wanCfg.toUpperCase() : '',
              onLineStatus: info.onLineStatus,
              _time: new Date().getTime()
            }
          })
        }
      } catch (e) {
      } finally {
        this.$refs.newGateway && this.$refs.newGateway.handleClose()
      }
    },
    // 点击查询,重置为页码1
    search (queryParams) {
      // eslint-disable-next-line no-unused-expressions
      this.$refs.table?.initPage()
      this.pagination.page = 1
      this.searchList(queryParams)
    },
    exportExcel () {
      this.exportLoading = true
      const params = _.cloneDeep(this.params)
      params.pageNum = null
      params.pageSize = null
      downloadMiotData(params).then(async res => {
        await this.$saveFileForBlob(res.data, `机器联网数据.xls`)
        this.$message.success('数据请求成功,请保存文件')
      }).finally(() => {
        this.exportLoading = false
      })
    }
  }
}
</script>

<style scoped>
.table-wrapper{
  flex: 1;
  height: 0;
}
</style>
